package org.becomingMd;

import java.io.*;
import java.net.Socket;

public class ServerReceiveFileThread extends Thread{
    private Socket socket;
    private static final String DEFAULT_SAVE_PATH = "E:\\testAPK"; // 默认文件保存目录
     public ServerReceiveFileThread(Socket socket)
    {
        this.socket = socket;
    }
    @Override
    public void run(){
         try {
             DataInputStream dis = new DataInputStream(socket.getInputStream());
             while (true) {

                  String fileName = dis.readUTF();
                  Long  fileLength = dis.readLong();
                  System.out.println("文件名：" + fileName + "文件大小：" + fileLength);

                 // 创建保存目录（如果不存在）
                 File saveDir = new File(DEFAULT_SAVE_PATH);
                 if (!saveDir.exists() && !saveDir.mkdirs()) {
                     throw new IOException("无法创建目录: " + DEFAULT_SAVE_PATH);
                 }

                 // 构建文件保存路径
                 String filePath = DEFAULT_SAVE_PATH + File.separator + fileName;
                 // 接收文件内容
                 try (FileOutputStream fos = new FileOutputStream(filePath)) {
                     byte[] buffer = new byte[4096];
                     long receivedBytes = 0;

                     while (receivedBytes < fileLength) {
                         int read = dis.read(buffer, 0, Math.min(buffer.length, (int) ( fileLength - receivedBytes )));

                         if (read == -1) break;
                         fos.write(buffer, 0, read);
                         receivedBytes += read;

                         // 显示传输进度（可选）
                         System.out.printf("接收进度: %.2f%%\r",
                                 (receivedBytes * 100.0) / fileLength);
                     }
                 }

                 System.out.println("\n文件保存成功：" + filePath);
             }
         } catch (EOFException e) {
             System.out.println("客户端正常断开连接：" + socket.getRemoteSocketAddress());
         } catch (IOException e) {
             System.err.println("网络传输异常：" + e.getMessage());
         } catch (Exception e) {
             System.err.println("处理异常：" + e.getMessage());
             e.printStackTrace();
         } finally {
             try {
                 socket.close();
             } catch (IOException e) {
                 System.err.println("关闭socket异常：" + e.getMessage());
             }
         }
    }
}